﻿using AutoMapper;
using MediatR;
using Newtonsoft.Json;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Photos
{
    public class PhotosSaveCommandHandler : IRequestHandler<PhotosSaveCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Photos> photosRepository;
        private readonly IMapper mapper;

        public PhotosSaveCommandHandler(IBaseRepository<T_Photos> photosRepository, IMapper mapper)
        {
            this.photosRepository = photosRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(PhotosSaveCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            if (request.IsAddOrDel == false)
            {
                result.Message = "上传成功";
                var model = mapper.Map<T_Photos>(request);
                result.Data = await photosRepository.Add(model);
                return await Task.FromResult(result);
            }
            else 
            {
                result.Message = "删除成功";
                var model = photosRepository.GetAll().FirstOrDefault(x => x.ImageUrl == request.ImageUrl);
                model.IsDelete = true;
                result.Data = await photosRepository.Update(model);
                return await Task.FromResult(result);
            }
           
        }
    }
}
